<?php
namespace app\admin\lib\exception;
use think\exception\Handle;
use think\facade\Env;
use think\Response;
use Throwable;

class ExceptionHandler extends Handle
{
    public $code;
    public $message;
    public $errorCode;
    public $data = [];

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException) {
            // 自定义异常
            $this->code = $e->code;
            $this->message = $e->message;
            $this->errorCode = $e->errorCode;
            $this->data = $e->data;
        } else {
            // 系统异常：调试模式返回详细信息，否则返回默认 data
            if (Env::get('APP_DEBUG')) {
                return parent::render($request, $e);
            }
            $this->code = 500;
            $this->message = '服务器异常';
            $this->errorCode = '10000';
            $this->data = [];
        }

        // 构造响应体（包含 data）
        $res = [
            'code'      => $this->code,
            'message'   => $this->message,
            'errorCode' => $this->errorCode,
            'data'      => $this->data
        ];
        return json($res, $this->code);
    }
}